﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Gear.ORM.Core.DeepDB;
using Gear.ToolKits.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;

namespace Gear.ORM.Core.Tenant
{
    /// <summary>
    /// 多租户帮助类
    /// </summary>
    public static class TenantTool
    {
        /// <summary>
        /// 租户ID获取
        /// </summary>
        /// <returns></returns>
        public static string GetTenantsId()
        {
            // 这里是你获取 TenantsId 的逻辑
            // 首先获取请求的 主机地址，然后根据主机地址查询对应的租户 TenantId，避免多次查询数据库，这里使用了 MemoryCacheHelper 内存缓存。
            var tenantid = MemoryCacheHelper.Get<string>("tenantid");

            if(string.IsNullOrEmpty(tenantid))
            {
                HttpContextAccessor context = new HttpContextAccessor();
                var local = context.HttpContext?.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.HttpContext?.Connection.LocalPort.ToString();
                // 根据local获取当前租户
                using (var pool = DeepPool.DeepSugar())
                {
                    // 判断没有租户记录则新增临时租户
                    tenantid = pool.Queryable<Tenants>().First(it => it.Host == local)?.TenantId;
                    tenantid ??= SetDefult(pool, local);
                    pool.Close();

                }
                
                MemoryCacheHelper.Cache.Set("tenantid", tenantid);

            }
            return tenantid;
            
        }

        /// <summary>
        /// 新增租户设置
        /// </summary>
        /// <returns></returns>
        private static string SetDefult(SqlSugarClient pool,string local) => pool.Insertable(new Tenants {
            TenantId = Guid.NewGuid().ToString(),
            Name = local+"租户",
            Host = local,
            CreatedTime = DateTime.Now,
            Schema = "gear" }).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntity().TenantId;
        }
}
